<?php
/*
[articles_id] => 
[articles_crt_date] => 
[articles_chg_date] => 
[articles_author_id] => 
[articles_editor_id] => последний редактор
[articles_category] => Категория
[articles_title] => Заголовок
[articles_text] => Текст, HTML
*/
$table = DB::$tables['message'];

if( isset( $_REQUEST['edit_row_id'] ) && is_array( $_REQUEST['edit_row_id']) && count( $_REQUEST['edit_row_id'])>0 ){
	$where = '`mess_id` IN '.DB::arrToSet( $_REQUEST['edit_row_id'] );
	
	/*  удалить  */
	if( isset($_REQUEST['delete_rows']) ){
		$result = DB::deleteFromTableWhere( $table, $where );
		$operationName = $_REQUEST['delete_rows'];
	}
	
	/*  отметить открытыми  */
	if( isset($_REQUEST['set_opened']) ){
		$result = DB::updateTableArrayWhere( $table, array( 'mess_open_date'=>date("Y-m-d H:i:s") ), $where.' AND `mess_open_date` IS NULL' );
		$operationName = $_REQUEST['set_opened'];
	}

	Page::message( 'success', null, Lang::get('OPERATION_IS_EXECUTED').': '.$operationName.' - '.$result['affected'] );	
}


/**/$whereStr = '';
	
	$likeCond = array( //  LIKE "%'.db_escape( $_REQUEST[ $name ]).'%"
		'mess_title',
		'mess_body',
		'mess_from_mail',
		'mess_to_mail',
		'mess_from_name',
		'mess_to_name',
	);
	foreach( $likeCond as $name )
		if(isset($_REQUEST[$name]) && strlen($_REQUEST[$name])>0)  $whereStr.= ' AND '.$name.' LIKE "%'.db_escape( $_REQUEST[ $name ]).'%"';

	if(isset($_REQUEST['mess_opened']) && strlen($_REQUEST['mess_opened'])>0){
		$whereStr.= ' AND mess_open_date '.( $_REQUEST['mess_opened']==0? 'IS NULL': 'IS NOT NULL' );
	}

	if(!empty($_REQUEST['mess_category']))  $whereStr.= ' AND mess_category="'.db_escape( $_REQUEST['mess_category']).'"';

	if(!empty($_REQUEST['mess_send_date_from']))	$whereStr.= ' AND TO_DAYS(mess_send_date)>=TO_DAYS("'.db_escape( $_REQUEST['mess_send_date_from'] ).'")';
	if(!empty($_REQUEST['mess_send_date_to']))	$whereStr.= ' AND TO_DAYS(mess_send_date)<=TO_DAYS("'.db_escape( $_REQUEST['mess_send_date_to'] ).'")';
	if(!empty($_REQUEST['mess_open_date_from']))	$whereStr.= ' AND TO_DAYS(mess_open_date)>=TO_DAYS("'.db_escape( $_REQUEST['mess_open_date_from'] ).'")';
	if(!empty($_REQUEST['mess_open_date_to']))	$whereStr.= ' AND TO_DAYS(mess_open_date)<=TO_DAYS("'.db_escape( $_REQUEST['mess_open_date_to'] ).'")';
	
	$alltable = exec_sql2array( 'SELECT '.
	'mess_id, '.
	'mess_send_date, '.
	'mess_open_date, '.
	'mess_from_id, '.
	'mess_to_id, '.
	'mess_from_mail, '.
	'mess_to_mail, '.
	'mess_from_name, '.
	'mess_to_name, '.
	'mess_category, '.
	'mess_title, '.
	'mess_body	'.	
	' FROM '.$table.' WHERE 1 '.$whereStr.' ORDER BY mess_send_date DESC');

$colTitle = array(
	'mess_id'=>'ID',
	'mess_send_date'=>'Отправлено',
	'mess_open_date'=>'Открыто',
	'mess_from_id'=>'От ID',
	'mess_to_id'=>'Для ID',
	'mess_from_mail'=>'От Mail',
	'mess_to_mail'=>'Для Mail',
	'mess_from_name'=>'От Имя',
	'mess_to_name'=>'Для Имя',
	'mess_category'=>'Категория',
	'mess_title'=>'Заголовок',
	'mess_body'=>'Текст',		
);
	
	if(count($alltable)>0){
		/*
		foreach( $alltable[0] as $name=>$value) {
			$title = !empty($colTitle[$name]) ? $colTitle[$name] : $name;
			switch($name){
				case 'page_load_from_db':
					$title='<span title="'.$title .'">'.'From DB'.'</span>';
				break;			
			}
			$th.='<th>'.$title.'</th>'."\n";
		}*/
		
		$th=''; $ths='';$trs=''; $num=0;
		foreach($alltable as $pageArr){
			 $tr=''; $num++;
			foreach($pageArr as $name=>$value) {
				//if( $name=='articles_author_id' || $name=='articles_editor_id') continue;
				$aId = $pageArr['mess_id'];
				
				switch($name){
					case 'mess_id':
						$value= '<input type="checkbox" name="edit_row_id[]" value="'.$aId.'">'.$value;
					break;
					case 'mess_body': 
						$preShow = strpos($value, ' ', 50); $preShow = $preShow?$preShow:100;
						$value = '<div onclick="var el=document.getElementById(\'atext'.$aId.'\'),sd=el.style.display; el.style.display=sd==\'\'?\'none\':\'\';" style="cursor:pointer" title="развернуть/свернуть">'.
							nl2br( substr($value, 0, $preShow )).
							'<span id="atext'.$aId.'" style="display:none;">'.nl2br( substr($value, $preShow )).'</span> <b>...</b>'.//
						'</div>'; 
					break;
				}
				
				$tr.='<td>'.$value.'</td>'."\n";
				
				if($ths==''){
					$title = !empty($colTitle[$name]) ? $colTitle[$name] : $name;
					switch($name){
						case 'page_load_from_db':
							$title='<span title="'.$title .'">'.'From DB'.'</span>';
						break;			
					}
					$th.='<th>'.$title.'</th>'."\n";				
				}
			}
			$trs.='<tr class="'.( $num%2?'':'odd' ).'" >'.$tr.'</tr>'."\n";
			$ths = $th;
		}
		
		$outTable = '<form method="post" name="table_edit_form" action="">'.
			'<table class="admin_table"><thead>'.$ths.'</thead><tbody>'.$trs.'</tbody></table>'.
			'<input type="checkbox" name="check_all" value="edit_row_id[]">'.
			'Отмеченные: '.
			'<input type="submit" class="confirm_submit" name="delete_rows" value="'.Lang::get('TO_DELETE').'">'.
			'<input type="submit" class="confirm_submit" name="set_opened" value="Отметить открытыми">'.
		'</form>';		
	}	
?>
<?php echo Page::outMessages(); //echo Form::outErrors( articles_form );?>

<div class="panel inline-block" id="articles_select_panel" style="display:<?php echo isset($_REQUEST['filter_posted'])?'':'none';?>">
	<form method="post" name="filter_form" action="">
	<input type="hidden" name="filter_posted" value="1">
	<p>
		От mail <input type="text" name="mess_from_mail" id="mess_from_mail" value="<?echo Form::requested('mess_from_mail');?>" >
	<!--/p><p-->
		Для mail <input type="text" name="mess_to_mail" id="mess_to_mail" value="<?echo Form::requested('mess_to_mail');?>" >
	</p>
	<p>
		От Имя <input type="text" name="mess_from_name" id="mess_from_name" value="<?echo Form::requested('mess_from_name');?>" >
	<!--/p><p-->
		Для Имя <input type="text" name="mess_to_name" id="mess_to_name" value="<?echo Form::requested('mess_to_name');?>" >
	</p>
	
	<p>
		Заголовок <input type="text" name="mess_title" id="mess_title" value="<?echo Form::requested('mess_title');?>" title="Заголовок" >
	<!--/p><p-->	
		Текст <input type="text" name="mess_body" id="mess_body" value="<?echo Form::requested('mess_body');?>" title="" >
	</p><p>	
		Категория <select name="mess_category" id="mess_category" title="Категория">
			<?php
				$opAr = array(''=>'')+Form::getEnumArray( 'message', 'mess_category');
				echo Form::createSelectOptions( 
					$opAr, ( isset( $_REQUEST['mess_category'] ) ? $_REQUEST['mess_category'] : '')
				);
			?>		
		</select>
	<!--/p><p-->	
		Просмотр <select name="mess_opened" id="mess_opened" title="">
			<?php
				echo Form::createSelectOptions( 
					array(''=>'', '0'=>'неоткрыто', '1'=>'открыто'),
					( isset( $_REQUEST['mess_opened'] ) ? $_REQUEST['mess_opened'] : '')
				);
			?>		
		</select>
	</p>
	<p>
		Отправлено 
		от <input type="text" name="mess_send_date_from" id="mess_send_date_from" value="<?echo Form::requested('mess_send_date_from');?>" title="формат: гггг-мм-дд">
		до <input type="text" name="mess_send_date_to" id="mess_send_date_to" value="<?echo Form::requested('mess_send_date_to');?>" title="формат:гггг-мм-дд">
	</p><p>
		Открыто  
		от <input type="text" name="mess_open_date_from" id="mess_open_date_from" value="<?echo Form::requested('mess_open_date_from');?>" title="формат:гггг-мм-дд">
		до <input type="text" name="mess_open_date_to" id="mess_open_date_to" value="<?echo Form::requested('mess_open_date_to');?>" title="формат:гггг-мм-дд">
	</p><p>	
		<input type="submit" name="submit" value="<?php echo Lang::get('TO_FIND');?>">
		<input type="button"  name="reset" value="<?php echo Lang::get('TO_RESET');?>" onclick="formLib.clearValues( this.form, 0, ['submit','reset'] )">
	</p>
	</form>
	<script type="text/javascript">
	var formRules = {};
	formRules['mess_send_date_from']=formRules['mess_send_date_to']=formRules['mess_open_date_from']=formRules['mess_open_date_to'] = { 
		label:'', 
		required: 0, 
		regexp: /^\d{4}-\d{2}-\d{2}$/,
		e_message: 'формат гггг-мм-дд',
		filter:{
			regexp: /^\d{0,4}-?\d{0,2}-?\d{0,2}$/,
			mask: '####-##-##'
		}
	};
	formLib.activateOnBlurElems( document.forms['filter_form'], formRules );
	formLib.activateFilters( document.forms['filter_form'], formRules, function( form, inpName, insSym, isError){
		var messStr = isError? 'символ "'+insSym+'" не подходит': '' ;
		formLib.outMess( form, inpName, messStr, formLib.errorClass );
	});
	</script>
</div><br>
<button onclick=";var el=document.getElementById('articles_select_panel'), sd=el.style.display; el.style.display=sd==''?'none':'';" title="развернуть/свернуть">Поиск...</button>
<hr>
<?php if(isset($outTable)) echo $outTable;?>